<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use \DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use \App\Http\Requests\UserPostRequest;
use Hash;
use Session;

class LoginsController extends Controller
{
    /**
     * 用户登录表单
     *
     * @return void
     */
    public function getLogin()
    {
       
        return view('admin.logins.login');
    }

    /**
     * 用户登录验证
     * $data 用户提交信息
     * @return void
     */
    public function postUserlogin(Request $request)
    {
        //获取用户登录信息
        $data = $request->except(['_token']);
        // dd($data);
        //匹配用户信息
        $res = DB::table('user')
        ->where('username',$data['username'] )
        ->first();
        //判断
        // dd($res);
        if($res){
            //密码匹配
            if(!Hash::check($data['password'],$res->password)){
                return back()->with('error','密码不正确');
            }
            //验证码匹配
            if(session('codes') != $data['codes']){
                return back()->with('error','验证码错误');
            }

            //判断用户权限
            if($res->auth<4 || $res->status == 1){
                return back()->with('error','账号权限不足');
            }
            //用户登录后id存储到session
            // session(['id' =>$res->id]);
            // session_start();
            $_SESSION['id'] = $res->id;
            // session(['id' => $res->id]);
            //修改用户登录ip和时间
            $row = DB::table('user')->where('id',$res->id)->update(['lastlogin'=>time(),'ip'=>$_SERVER['REMOTE_ADDR']]);
            // dd($row);
            //查询用户头像
            return redirect('admin');   
        }else{
            return back()->with('error','登录失败');
        }
    }

    
}
